package com.zziq.cloudpicturebank.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zziq.cloudpicturebank.config.UserAvatarProperties;
import com.zziq.cloudpicturebank.constant.UserConstant;
import com.zziq.cloudpicturebank.exception.BusinessException;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.manager.auth.model.StpKit;
import com.zziq.cloudpicturebank.mapper.UserMapper;
import com.zziq.cloudpicturebank.model.dto.user.UserQueryRequest;
import com.zziq.cloudpicturebank.model.dto.user.UserUpdateMyRequest;
import com.zziq.cloudpicturebank.model.entity.User;
import com.zziq.cloudpicturebank.model.entity.VipCode;
import com.zziq.cloudpicturebank.model.enums.SvipAndVipEnum;
import com.zziq.cloudpicturebank.model.enums.UserRoleEnum;
import com.zziq.cloudpicturebank.model.vo.user.LoginUserVO;
import com.zziq.cloudpicturebank.model.vo.user.UserVO;
import com.zziq.cloudpicturebank.service.UserService;
import com.zziq.cloudpicturebank.service.VipCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author Mr·张
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-02-20 15:53:04
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @javax.annotation.Resource
    private UserAvatarProperties userAvatarProperties;

    @javax.annotation.Resource
    private ResourceLoader resourceLoader;

    @javax.annotation.Resource
    private VipCodeService vipCodeService;

    @javax.annotation.Resource
    private TransactionTemplate transactionTemplate;



    /**
     * 用户注册
     *
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2. 检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 3. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        // 随机选择一个头像地址
        String randomAvatarUrl = getRandomAvatar();
        user.setUserAvatar(randomAvatarUrl);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    /**
     * 密码加密
     *
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "zziq";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 查询用户是否存在
        User user = this.lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, encryptPassword).one();
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userAccount", userAccount);
//        queryWrapper.eq("userPassword", encryptPassword);
//        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        // 4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，
        // 注意保证该用户信息与 Spring Session 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前脱敏后的登录的用户信息
     *
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        StpKit.SPACE.logout();
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取脱敏后的用户信息
     *
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     *
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     * 根据查询请求 转为QueryWrapper 对象
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 判断是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public boolean updateMyUser(UserUpdateMyRequest userUpdateMyRequest, User loginUser) {
        String userOldPassword = userUpdateMyRequest.getUserOldPassword();
        String userNewPassword = userUpdateMyRequest.getUserNewPassword();
        String userCheckPassword = userUpdateMyRequest.getUserCheckPassword();
        String encryptNewPassword = "";
        //判断是否需要修改密码
        if (userOldPassword != null && userNewPassword != null && userCheckPassword != null){
            //需要修改密码，开始校验
            String encryptOldPassword = getEncryptPassword(userOldPassword);
            //校验旧密码
            ThrowUtils.throwIf(!encryptOldPassword.equals(loginUser.getUserPassword()), ErrorCode.OPERATION_ERROR, "旧密码错误");
            //校验新密码
            if (userNewPassword.length() < 8) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码最少8位");
            }
            if (!userNewPassword.equals(userCheckPassword)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "两次输入的新密码不一致");
            }
            //校验新旧密码是否相同
            ThrowUtils.throwIf(userOldPassword.equals(userNewPassword), ErrorCode.OPERATION_ERROR, "新旧密码不能相同");
            encryptNewPassword = getEncryptPassword(userNewPassword);
        }

        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        if (!"".equals(encryptNewPassword)){
            user.setUserPassword(encryptNewPassword);
        }
        boolean result = this.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return true;
    }

    /**
     * 随机选择一个头像地址
     * @return 随机头像地址
     */
    private String getRandomAvatar() {
        List<String> defaultAvatarList = userAvatarProperties.getDefaultAvatars();
        if (defaultAvatarList == null || defaultAvatarList.isEmpty()) {
            return "";
        }

        Random random = new Random();
        int randomIndex = random.nextInt(defaultAvatarList.size());
        return defaultAvatarList.get(randomIndex);
    }

    /**
     * 兑换会员
     *
     * @param loginUser
     * @param vipCodeContent
     * @return
     */
    @Override
    public boolean exchangeVip(User loginUser, String vipCodeContent) {
        // 1. 参数校验
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR, "用户未登录");
        ThrowUtils.throwIf(StrUtil.isBlank(vipCodeContent), ErrorCode.PARAMS_ERROR, "兑换码无效");
        //管理员不能兑换会员
        ThrowUtils.throwIf(isAdmin(loginUser), ErrorCode.PARAMS_ERROR, "管理员不能兑换会员（管理员默认是超级会员）");
        // 2. 读取并校验兑换码
        VipCode vipCode = vipCodeService.lambdaQuery()
                .eq(VipCode::getCode, vipCodeContent)
                .one();
        ThrowUtils.throwIf(vipCode == null, ErrorCode.PARAMS_ERROR, "兑换码无效");
        ThrowUtils.throwIf(!vipCode.getType().equals(SvipAndVipEnum.VIP.getValue())
                && !vipCode.getType().equals(SvipAndVipEnum.SVIP.getValue())  ,
                ErrorCode.OPERATION_ERROR, "兑换码类型错误");
        ThrowUtils.throwIf(vipCode.getStatus() == 1, ErrorCode.PARAMS_ERROR, "兑换码已使用");
        //如果用户已经是超级会员，并且兑换码是普通会员，则不允许使用
        ThrowUtils.throwIf(
                UserConstant.SVIP_ROLE.equals(loginUser.getUserRole())
                        && SvipAndVipEnum.VIP.getValue().equals(vipCode.getType()),
                ErrorCode.OPERATION_ERROR, "已经是超级会员，不能兑换普通会员");
        // 3. 更新用户信息
        transactionTemplate.execute(status -> {
            //1.更新兑换码状态
            boolean res = vipCodeService.lambdaUpdate()
                    .eq(VipCode::getCode, vipCodeContent)
                    //使用乐观锁
                    .eq(VipCode::getStatus, 0)
                    .set(VipCode::getStatus, 1)
                    .set(VipCode::getUserId, loginUser.getId())
                    .set(VipCode::getUsedTime, new Date())
                    .update();
            ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "兑换失败，操作数据库失败！");

            //2.更新用户信息
            //构建更新对象
            User updateUser = new User();
            updateUser.setId(loginUser.getId());
            updateUser.setVipCode(vipCodeContent);
            // 2.1如果兑换码是超级会员兑换码
            if (SvipAndVipEnum.SVIP.getValue().equals(vipCode.getType())) {
                //如果用户已经是超级会员，则更新用户的vipExpireTime字段
                if (UserConstant.SVIP_ROLE.equals(loginUser.getUserRole())) {
                    //更新用户过期时间为当前过期时间加 1 年
                    updateUser.setVipExpireTime(DateUtil.offsetMonth(loginUser.getVipExpireTime(), 12));
                }else if (UserConstant.VIP_ROLE.equals(loginUser.getUserRole())) {
                    //用户当前是普通会员，则更新用户角色为超级会员，并设置过期时间为当前时间加 1 年
                    updateUser.setUserRole(UserConstant.SVIP_ROLE);
                    //设置过期时间为当前时间加 1 年
                    updateUser.setVipExpireTime(DateUtil.offsetMonth(new Date(), 12));
                }
                //用户当前不是超级会员，则更新用户角色为超级会员，并设置过期时间
                else {
                    //设置用户角色为超级会员
                    updateUser.setUserRole(UserConstant.SVIP_ROLE);
                    //设置过期时间为当前时间加 1 年
                    updateUser.setVipExpireTime(DateUtil.offsetMonth(new Date(), 12));
                }
            }
            // 2.2如果兑换码是普通会员兑换码
            else {
                //如果用户已经是普通会员，则更新用户的vipExpireTime字段
                if (UserConstant.VIP_ROLE.equals(loginUser.getUserRole())) {
                    //更新用户过期时间为当前过期时间加 1 年
                    updateUser.setVipExpireTime(DateUtil.offsetMonth(loginUser.getVipExpireTime(), 12));
                }else {
                    //设置用户角色为普通会员
                    updateUser.setUserRole(UserConstant.VIP_ROLE);
                    //设置过期时间为当前时间加 1 年
                    updateUser.setVipExpireTime(DateUtil.offsetMonth(new Date(), 12));
                }
            }
            // 执行更新
            boolean updatedRes = this.updateById(updateUser);
            ThrowUtils.throwIf(!updatedRes, ErrorCode.OPERATION_ERROR, "兑换失败，操作数据库失败！");
            return true;
        });
        return true;
    }


    /**
     * 查询过期的VIP用户
     * @param currentDate
     * @return
     */
    @Override
    public List<User> listExpiredVipUsers(Date currentDate) {
        return this.list(
                new QueryWrapper<User>()
                        .eq("userRole", "vip")
                        .or()
                        .eq("userRole", "svip")
                        .lt("vipExpireTime", currentDate)
        );
    }
}




